﻿using UnityEngine;
using System.Collections;


[ExecuteInEditMode]
public class SelectiveBlurMask : MonoBehaviour 
{

	public Shader			ShaderLink = null;

	RenderTexture			mRT = null;
	GameObject				mShaderCameraGo = null;



	void Awake()
	{
		Shader.SetGlobalFloat( "_BlurAmount", 0.0f );
	}


	// Use this for initialization
	void Start () 
	{
		if( ( this.ShaderLink == null ) ||
			( this.ShaderLink.isSupported == false ) )
		{
			this.enabled = false;
			return;
		}	
	}

	void OnDisable()
	{
		GameObject.DestroyImmediate ( this.mShaderCameraGo );
	}


	void OnPreCull()
	{
		if( ( this.enabled == false ) ||
			( this.gameObject.activeSelf == false ) )
		{
			return;
		}

		this.mRT = RenderTexture.GetTemporary( (int)this.camera.pixelWidth, (int)this.camera.pixelHeight, 24, RenderTextureFormat.ARGB32 );
		if( this.mShaderCameraGo == null )
		{
			this.mShaderCameraGo = new GameObject( "CameraBlurBuffer", typeof( Camera ) );
			this.mShaderCameraGo.camera.enabled = false;
			this.mShaderCameraGo.hideFlags = HideFlags.HideAndDontSave;
		}

		Camera cam = this.mShaderCameraGo.camera;
		cam.CopyFrom( this.camera );
		cam.backgroundColor = new Color( 0, 0, 0, 1 );
		cam.clearFlags = CameraClearFlags.SolidColor;
		cam.targetTexture = this.mRT;
		cam.RenderWithShader( this.ShaderLink, "RenderType" );		

		Shader.SetGlobalTexture( "_GlobalBlurBufferTexture", this.mRT );
		Shader.SetGlobalVector( "_GlobalBlurBufferTextureSize", new Vector4( this.mRT.width, this.mRT.height, 0, 0 ) );
	}

	void OnPostRender()
	{
		if( ( this.enabled == false ) ||
			( this.gameObject.activeSelf == false ) )
		{
			return;
		}
		RenderTexture.ReleaseTemporary( this.mRT );
	}

}
